import { piniaStore } from '../store'
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => {
    return {
      userInfo: {
        avatar: '',
        name: '',
        profile: '',
        isdriver: 0
      }
    }
  },
  getters: {
    getUserInfo: (state) => state.userInfo
  },
  actions: {
    setUserInfo(info) {
      const profile = info && info.profile ? info.profile : ''
      const avatarUrl = profile ? `${import.meta.env.VITE_APP_API_BASEURL}${profile}` : ''
      this.userInfo = {
        ...this.userInfo,
        ...info,
        avatar: avatarUrl,
        isdriver: info && typeof info.isdriver !== 'undefined' ? info.isdriver : this.userInfo.isdriver
      }
    },
    // 从缓存初始化用户信息
    initUserInfoFromCache() {
      try {
        const { UserInfoManager } = require('@/utils/userInfo')
        const userInfo = UserInfoManager.getUserInfo()
        if (userInfo) {
          this.setUserInfo(userInfo)
        }
      } catch (e) {
        console.error('Failed to init user info from cache:', e)
      }
    }
  }
})

export function useOutsideAppStore() {
  return useAppStore(piniaStore)
}
